<?php
namespace control;
//管理员后台 - 用户管理
class userClass extends adIndexClass
{
    private const page = 'user'; # 权限
    private const table = 'user'; # 数据表
    private const title = '用户信息';

    /*成本表列表-查询条件*/
    public function home()
    {
        $html =
            text(["name" => "name", "title" => L('setting.table.xing_ming')]) .
            text(["name" => "tel", "title" => L('setting.table.shou_ji_hao')]) .
            text(["name" => "userName", "title" => L('setting.table.yong_hu_ming')]) .
            select(["name" => "state", "title" => L('setting.table.zhuang_tai'), 'option' => ['启用', '停用']]);
        //返回
        return $this->homeFun($this->search($html));
    }

    /*成本表列表-查询结果*/
    public function homeSearch()
    {
        $where = ' 1=1 ';
        $equal = [
            'state' => $this->post('state'),
        ];
        $like = [
            'name' => $this->post('name'),
            'tel' => $this->post('tel'),
            'userName' => $this->post('userName'),
        ];
        $where .= search([
            "=" => $equal,
            "like" => $like,
        ]);

        $orderBy = ' time DESC';
        //获取查询结果
        $page = $this->page([
            "table" => self::table,
            "where" => $where,
            "order" => $orderBy,

        ]);
        //获取表头
        $checkAll = $this->checkAll("listForm", "id");
        $tr[] = [$checkAll, L('setting.table.xing_ming'), L('setting.table.shou_ji_hao'), L('setting.table.yong_hu_ming'), L('setting.table.role'), L('setting.table.zhuang_tai')];
        //获取记录
        $url = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail";
        foreach ($page['array'] as $array) {
            $dominate = [
                "box" => [
                    "name" => "id",
                    "value" => $array['uid']
                ],
                "detail" => [
                    "title" => L('setting.table.yhxq'),
                    "click" => "newIframe('".L('setting.table.yhxq')."','" . $url . "&id=" . $array['uid'] . "')"
                ],
            ];
            $tr[] = [$this->dominate($dominate), $array['name'], $array['tel'], $array['userName'], self::getRoleName($array['role']), $array['state']];
        }
        //控件
        $button = '';
        if ($this->power(self::page, "edit")) {
            $button .= "<span class='spanButton' onclick=\"newIframe('".L('setting.table.xjyh')."', '" . $this->root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=editPage&id=' . suiji() . "')\">新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        if ($this->power(self::page, "state")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'changeState', state: '启用' })\">启用</span>\n";
        }
        if ($this->power(self::page, "state")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'changeState', state: '停用'})\">停用</span>\n";
        }
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . space . $this->tableMany(array("tr" => $tr)) . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 获取角色名称
     *
     * @param string $ids
     */
    public static function getRoleName($ids)
    {
        $roleName = '';
        $roleArray = (array)json_decode($ids, true);
        foreach ($roleArray as $rid) {
            $role = query('role', " id = '$rid' ");
            $roleName .= isset($role['name']) ? ($role['name'] . ';') : '';
        }
        return $roleName;
    }


    /**
     * 新建
     *
     * @return void
     */
    public function detail()
    {
        $info = query(self::table, " uid = '" . $this->get('id') . "' ");
        if (!$this->power(self::page, "see")) {
            $html = L('setting.table.nmzckzx');
        } elseif (!$this->get('id')) {
            $html = L('setting.table.id_empty');
        } elseif (!$info['uid']) {
            $html = L('setting.table.wzdcxx');
        } else {
            $data = [
                "id" => $info['uid'],
            ];
            //按钮
            $button = [];
            if ($this->power(self::page, "edit")) {
                $button[] = [
                    "name" => L('setting.table.shan_chu'),
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'del', "id" => $info['uid']],
                ];
                $opt = ($info['state']) == '停用' ? '启用' : '停用';
                $button[] = [
                    "name" => $opt,
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'changeState', "id" => $info['uid'], 'state' => $opt],
                ];
                $button[] = [
                    "name" => L('setting.table.edit'),
                    "type" => "顶部页卡",
                    "title" => L('setting.table.edit'),
                    "url" => $this->root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=editPage&id=' . $info['uid'],
                    'style' => 'li-btn-blue-bg',
                ];
            }
            //生成表单
            $data['html'] = $this->tableShow([
                "button" => $button,
                L('setting.table.ji_ben_xin_xi') => [
                    [
                        L('setting.table.xing_ming') => $info['name'],
                        L('setting.table.shou_ji_hao') => $info['tel'],
                        L('setting.table.yong_hu_ming') => $info['userName'],
                    ],
                    [
                        "角色" => self::getRoleName($info['role']),
                    ],
                    [
                        L('setting.table.bei_zhu') => "<pre>" . kong($info['text']) . "</pre>",
                    ],
                ],
                L('setting.table.xi_tong_xin_xi') => [
                    [
                        L('setting.table.yhbh') => $info['userNo'],
                        L('setting.table.chuang_jian_ren') => self::findStaff($info['stid'], 'name'),
                        L('setting.table.cjsj') => $info['time'],
                    ],
                    [
                        L('setting.table.gxsj') => $info['updateTime'],
                        L('setting.table.zhuang_tai') => $info['state'],
                    ],
                ]
            ]);
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }

    public function editPage()
    {
        $id = $this->get('id')?:suiji();
        $info = query(self::table, " uid = '" . $id . "' ");
        if ($this->get('staffId')){
            $staff = query('staff',"stid = '".$this->get('staffId')."'");
            $info['tel'] = $staff['tel'];
            $info['name'] = $staff['name'];
        }
        // 员工
        $staffOption = [];
        $result = find(['table' => 'staff', 'where' => "state !='离职'"]);
        foreach ($result['array'] as $val) {
            $staffOption[$val['stid']] = $val['name'];
        }
        // 角色
        $roleOption = [];
        $role = find(['table' => 'role', 'where' => ' 1=1 ']);
        foreach ($role['array'] as $val) {
            $roleOption[$val['id']] = $val['name'];
        }
	    $button[]  = [
		    "name"  => L('public.submit'),
		    "type"  => "点击事件",
		    "cla"   => $this->get('cla'),
		    "fun"   => "subForm('" . self::page . "EditPageForm', root+'control/adIndex.html?cla=" . self::page . "&fun=editPageEdit')",
		    "post"  => ["id" => $this->get('id')],
		    'style' => 'li-btn-blue-bg',
	    ];
	    $button[]  = [
		    "name"  => L('public.saveDraft'),
		    "type"  => "点击事件",
		    "cla"   => $this->get('cla'),
		    "fun"   => "saveTemp('" . self::page . "', 'editPage', '" . self::page . "EditPageForm')",
		    "post"  => ["id" => $this->get('id')],
		    'style' => 'li-btn-green-bg',
	    ];
        //表单
        $data['html'] = $this->layerEdit([
            "table" => [
                [
                    must . "姓名：" => selectMultiple([
                            "name" => "stid",
                            "title" => L('setting.table.yuan_gong'),
                            'value' => $info['stid']?:$this->get('staffId'),
                            'class' => 'textLong',
                            'option' => $staffOption,
                            'change' => 'getUserTel',
                        ])
                        . hidden(['name' => 'name', 'value' => $info['name']]),
                ],
                [
                    "手机号：" => '<span id="editPage-tel">' . $info['tel'] . '</span>' . hidden(['name' => 'tel', 'value' => $info['tel']]),
                ],
                [
                    must . "用户名：" => text(["name" => "userName", 'class' => 'textLong', "value" => $info['userName']]),
                ],
                [
                    "密码：" => hidden(['name' => 'password', 'value' => '']) . (!empty($info['uid']) ? "<span id='pwd'>***********</span><span class='spanButton' style='margin: 0 0 0 20px' id='copy-btn' data-pas>重置并复制</span>" : para('staffPas') . ' (初始密码)'),],
                [
                    must . "角色：" => checkbox(["name" => "role", 'class' => 'textLong', 'value' => $roleOption, "checked" => json_decode($info['role'], true)]),
                ],
                [
                    "备注：" => textarea(["name" => "text", "value" => $info['text']])
                        . hidden(['name' => 'id', 'value' => $info['uid'] ?:$id]),
                ],
                [
	                $this->tableShowButton($button),
                ],
            ],
            'button' => ' ',
        ]);

        $html = <<<EOT
        <script src='{$this->root}static/javascript/clipboard.min.js'></script>
        <script>
        var pageCtrl = {
            getPass: function(ele) {
                $.ajax({
                    url: root + 'control/adIndex.html?cla=user&fun=resetPwd',
                    type: 'post',
                    data: {
                        id : $('[name="id"]').val()
                    },
                    dataType: 'json',
                    async: false,
                    success: function(res) {
                        if(res.code == 1){
                            ele.html(res.data)
                        }else{
                            msg(res.msg, 'error')
                        }
                    }
                });
            },
            clip: function() {
                let that = this,
                clipboard = new ClipboardJS('#copy-btn', {
                    text: function(el) {
                        let obj = $('#pwd')
                        obj.empty()
                        that.getPass(obj); //ajax请求并设置要复制的字符串
                        return obj.html()
                    }
                });
                clipboard.on('success', function(e) {
                    console.log(e)
                    msg(L('setting.table.mmfzcg'))
                    e.clearSelection();
                });
                clipboard.on('error', function(e) {
                    console.log(e)
                    msg(L('setting.table.mmfzsbqsdfz'), 'error')
                    e.clearSelection();
                });
            },

            init: function() {
                this.clip();
            }
        };
        $(function() {
            pageCtrl.init();
        });
        function getUserTel(obj) {
            let id = $(obj).find("option:selected").val()
            if(id.length>0){
                $('[name="name"]').val($(obj).find("option:selected").text())
                $.post(root+'control/adIndex.html?cla=user&fun=getUserTel', {id: id}, function(res){
                    if(res.warn === 1){
                        $('[name="tel"]').val(res.data)
                        $('#editPage-tel').html(res.data)
                    }
                },'json')
            }
        }
        </script>
EOT;
        //返回
        return $this->tab($data) . $html;
    }

    public function resetPwd()
    {
        $id = $this->post('id') ? $this->post('id') : '';
        $data = [
            'code' => 0
        ];
        if (!$id) {
            $data['warn'] = L('setting.table.csbnwk');
        } elseif (!$this->power(self::page, "edit")) {
            $data['warn'] = "你没有编辑" . self::title . "的权限";
        } else {
//            $password = para('staffPas');
            $password=mt_rand(10000001,99999999);
            $data['warn'] = static::update([
                'table' => self::table,
                'field' => [
                    'password' => md5s($password),
                    'loginError' => 0
                ],
                'where' => " uid = '$id' "
            ]);
            if (in_array($data['warn'], ['更新成功', '新增成功'])) {
                $data = [
                    'msg' => L('setting.table.mmzzcg'),
                    'data' => $password,
                    'code' => 1
                ];
            }
        }
        return json_encode($data, 320);
    }

    public function getUserTel()
    {
        $id = $this->post('id') ? $this->post('id') : '';
        $json = [];
        if (!$id) {
            $json['warn'] = L('setting.table.csbnwk');
        } else {
            $json['warn'] = 1;
            $json['data'] = $this->findStaff($id, 'tel');
        }
        return json_encode($json, 320);
    }

    /*成本表基本资料新增或修改-异步处理*/
    public function editPageEdit()
    {
        $id = $this->post('id') ?: self::getId();
        $field = [
            'stid' => $this->post('stid'),
            'name' => $this->post('name'),
            'userName' => $this->post('userName'),
            'role' => $this->post('role') ? json_encode($this->post('role'), 320) : '',
            'tel' => $this->post('tel'),
            'text' => $this->post('text'),
        ];
        $annotation = [
            'stid' => L('setting.table.staffId'),
            'name' => L('setting.table.xing_ming'),
            'userName' => L('setting.table.yong_hu_ming'),
            'role' => L('setting.table.role'),
            'tel' => L('setting.table.shou_ji_hao'),
            'password' => L('setting.table.mi_ma'),
            'text' => L('setting.table.bei_zhu'),
        ];
        $rules = [
            'stid' => 'required',
            'name' => 'required',
            'userName' => 'required',
            'role' => 'required',
            'tel' => 'required|unsigned_int',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        $where = " uid = '$id' ";
        $info = query(self::table, $where);
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = L('setting.table.user_edit_permission');
        } else {
            // 非无限用户 设定用户数
            $users = (int)para('userNumberLimit');
            if ($users != -1) {
                // 已有用户数
                $total = static::total(['table' => 'user', 'where' => " 1=1 "]);
                if ($total >= $users) {
                    $json['warn'] = str_replace(['{{num}}'], [$users], L('setting.table.user_new_warn'));
                    goto resp;
                }
            }
            if (sqlNum(self::table, " (userName = '{$field['userName']}' OR tel = '{$field['tel']}') AND uid <> '$id'   ") > 0) {
                $json['warn'] = str_replace(['{{name}}', '{{tel}}'], [$field['userName'], $field['tel']], L('setting.table.user_repeat'));
                goto resp;
            }

            // 密码不为空
            if ($this->post('password')) {
                $field['password'] = md5s($this->post('password'));
            }
            if (!$info['uid']) {
                $userNo = codeTemplateClass::generateCode('user', [
                    'prefix' => 'UID' . date('Ymd'),
                    'table' => 'user',
                    'field' => 'userNo',
                    'where' => '',
                ], $field);
                $field = array_merge($field, [
                    'uid' => $id,
                    'userNo' => $userNo,
                    'password' => md5s(para('staffPas')),
                    'operator' => $this->control['stid'],
                    'state' => '启用',
                    'time' => $this->time
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field,]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where
                ]);
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = str_replace(['{{staffName}}', '{{name}}', '{{id}}'], [$this->control['name'], $field['name'], $id], L('setting.table.user_edit_text'));
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
            }
        }

        resp:
        return json_encode($json, 320);
    }

    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $append = [];
        switch ($act) {
            case 'changeState':
                $act = 'state';
                $msg = self::title . L('setting.table.xgzt');
                $title = self::table . 'Change';
                $function = 'changeState';
                $form = 'userOperateForm, listForm';
                if ($this->post('state')) {
                    $append = [
                        0 => hidden(['name' => 'state', 'value' => $this->post('state')])
                    ];
                }
                $power = '';
                break;
            default:
                $act = 'del';
                $msg = L('setting.table.user_del_title');
                $title = self::table . 'Delete';
                $function = 'isDelete';
                $form = 'userOperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = str_replace(['{{msg}}'], [$msg], L('jon.other.permission_warn'));
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
                'append' => $append,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 修改状态
     */
    public function changeState()
    {
        $array = $this->post('listId') ?? $this->post('id');
        $state = $this->post('state');
        $act = 'state';
        $json = [];
        if (!$this->power(self::page, $act)) {
            $json['warn'] = L('setting.table.nmzczxdzx');
        } elseif (empty($array)) {
            $json['warn'] = L('setting.table.nytjldmzxzn');
        } else {
            $text = '';
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            // 修改field
            $fieldKey = 'state';
            foreach ($array as $id) {
                $where = " uid = '$id' ";
                $info = query(self::table, $where);
                if ($info['uid']) {
                    if ($info['state'] == $state) {
                        continue;
                    }
                    $fieldVlaue = ($info['state'] == '启用') ? '停用' : '启用';
                    // 修改状态
                    static::update([
                        "table" => self::table,
                        'field' => [
                            $fieldKey => $fieldVlaue
                        ],
                        "where" => $where
                    ]);
                    //添加记录
                    $text .= str_replace(['{{staffName}}', '{{name}}', '{{id}}'], [$this->control['name'], $info['name'], $info['uid']], L('setting.table.user_change_text')) . "<br>";
                    $x++;
                }
            }
            // 写入日志
            $this->logText(["type" => self::page, "text" => $text]);
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('setting.table.user_change_log'));
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        resp:
        return json_encode($json, 320);
    }


    // 确认删除信息
    public function isDelete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = L('setting.table.user_del_permission');
        } elseif (empty($array)) {
            $json['warn'] = L('setting.table.nytjldmzxzn');
        } else {
            $text = '';
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            // 判断field
            $fieldKey = 'state';
            $fieldVlaue = '启用';

            foreach ($array as $id) {
                $where = " uid = '$id' ";
                $info = query(self::table, $where);
                if ($info['uid']) {
                    if ($info[$fieldKey] == $fieldVlaue) {
                        $text .= str_replace(['{{name}}'], [$info['name']], L('setting.table.user_del_warn_one')) . "<br>";
                        continue;
                    }
                    if ($info['isDel']) {
                        $text .= str_replace(['{{name}}'], [$info['name']], L('setting.table.user_del_warn_two')) . "<br>";
                        continue;
                    }
                    // 删除表
                    delete([
                        "table" => self::table,
                        "where" => $where
                    ]);
                    //添加记录
                    $text .= str_replace(['{{staffName}}', '{{name}}', '{{id}}'], [$this->control['name'], $info['name'], $id], L('setting.table.user_del_text')) . "<br>";
                    $x++;
                }
            }

            // 写入日志
            $this->logText(["type" => self::page, "text" => $text]);
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('setting.table.user_del_msg'));
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }

        resp:
        return json_encode($json, 320);
    }
}
